/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.click.app.webapp.action;

import com.click.app.model.Cart;
import com.click.app.model.Catalog;
import com.click.app.model.Category;
import com.click.app.model.LabelValue;
import com.click.app.model.Product;
import com.click.app.model.RequestClient;
import com.click.app.model.StorageProduct;
import com.click.app.model.User;
import com.click.app.service.CartManager;
import com.click.app.service.CatalogManager;
import com.click.app.service.GenericManager;
import com.click.app.service.RequestClientManager;
import com.click.app.service.StorageProductManager;
import com.click.app.service.UserManager;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * @author orgale
 */
public class CartAction extends BaseAction {

    private CartManager cartManager;
    private CatalogManager catalogManager;
    private StorageProductManager storageProductManager;
    private RequestClientManager requestClientManager;
    private GenericManager<Product, Long> productManager;
    private UserManager userManager;
    private List carts;
    private Cart cart;
    private Long id;
    private String name;
    private List<Category> listCategories;

    public void setId(Long id) {
        this.id = id;
    }

    public Cart getCart() {
        return cart;
    }

    public void setCart(Cart cart) {
        this.cart = cart;
    }

    public List<String> getProductNames() {
        List<String> names = new ArrayList<String>();
        List<Product> ps = productManager.getAll();

        for (Product p : ps) {
            names.add(p.getName());
        }

        return names;
    }

    public float getTp() {
        if ((getSession().getAttribute("cart") == null) || (((Cart) (getSession().getAttribute("cart"))).getTotalPrice() == null)) {
            return 0.0f;
        }
        return ((Cart) getSession().getAttribute("cart")).getTotalPrice();
    }
    /*
    public boolean productsFree(Cart dis) {
    boolean resp = true;

    List<Product> mats = productManager.getAll();
    for (Product m : mats) {
    for (Cart d : m.getListCarts()) {
    if (d.equals(dis)) {
    resp = false;

    }
    }
    }

    return resp;
    }
     */

    public String delete() {
//        if (productsFree(cart)) {
        cartManager.remove(new Long(cart.getId()));
        saveMessage(getText("cart.deleted"));
        //      } else {
        //          List messages = (List) getRequest().getSession().getAttribute("errors");
        //        if (messages == null) {
        //          messages = new ArrayList();
        //    }
        //        messages.add(getText("cart.deleteError"));
        //      getRequest().getSession().setAttribute("errors", messages);

        //     }
        return SUCCESS;
    }

    public List<LabelValue> getProductsNamesAndValues() {
        List<LabelValue> namesAndValues = new ArrayList<LabelValue>();
        List<Product> ps = productManager.getAll();

        for (Product p : ps) {
            namesAndValues.add(new LabelValue(p.getName(), p.getId().toString()));
        }
        return namesAndValues;

    }

    public void setCatalogManager(CatalogManager catalogManager) {
        this.catalogManager = catalogManager;
    }

    public LabelValue getPos(List<LabelValue> lp, Product pr) {
        for (LabelValue lv : lp) {
            if (pr.getName().matches(lv.getLabel()) && (pr.getId().toString().matches(lv.getValue()))) {
                return lv;
            }
        }
        return null;
    }

    public String listCatalog() {
        System.out.println("PortalAction -> listCatalog()");
        if (getRequest().getRemoteUser() != null) {
            User u = userManager.getUserByUsername(getRequest().getRemoteUser());
            getRequest().setAttribute("currentRole", u.getRoles().size());
        }
        Catalog catalog = catalogManager.findCurrentCatalog();
        if (catalog != null) {
            setListCategories(catalog.getCategorys());
        } else {
            setListCategories(new ArrayList<Category>());
        }
        for (Category category : getListCategories()) {
            System.out.println(category);
//            for (Product p : category.getProducts()) {
        //              System.out.println("\t" + p);
        //        }
        }
        System.out.println("PortalAction -> end listCatalog()");
        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            cart = cartManager.get(id);
        } else {
            cart = new Cart();
            Date n = new Date();
        }

        return SUCCESS;
    }
    /*
    public boolean validationPasses() {
    boolean vp = true;
    if (cart.getName() == null || cart.getName().matches("")) {
    //errorMessage("Campo requerido, nombre.");
    vp = false;
    }
    if (cart.getDescription() == null || cart.getDescription().matches("")) {
    //errorMessage("Campo requerido, valor.");
    vp = false;
    }
    System.out.println("val:"+vp);
    return vp;
    }
     */

    public String sar() throws Exception {
        System.out.println("hola mundo!");
        return SUCCESS;
    }

    public String save() throws Exception {
        System.out.println("Saving cart...");
        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }
        cart = (Cart) getSession().getAttribute("cart");
        boolean isNew = (cart.getId() == null);
        List<RequestClient> rcs = new ArrayList<RequestClient>();
        rcs.addAll(cart.getRequests());
        cart.getRequests().clear();

        cart = cartManager.save(cart);

        for (RequestClient rc : rcs) {
            for (Product p : rc.getProducts()) {
                StorageProduct sp = p.getStorageProduct();
                sp.decrementStok(rc.getQuantity().intValue());
                storageProductManager.save(sp);
            }
            rc.setCart(cart);
            requestClientManager.save(rc);
            cart.getRequests().add(rc);
        }
        String key = (isNew) ? "cart.added" : "cart.updated";
        //saveMessage(getText(key));
        getSession().setAttribute("cart", null);
        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

    public void setCartManager(CartManager cartManager) {
        this.cartManager = cartManager;
    }

    public void setStorageProductManager(StorageProductManager storageProductManager) {
        this.storageProductManager = storageProductManager;
    }

    public void setRequestClientManager(RequestClientManager requestClientManager) {
        this.requestClientManager = requestClientManager;
    }

    public void setProductManager(GenericManager<Product, Long> productManager) {
        this.productManager = productManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public List getCarts() {
        return carts;
    }

    public String getItems() {
        Cart c = (Cart) getSession().getAttribute("cart");
        if (c != null) {
            return c.getTotalPrice().toString();
        }
        return "0.0";
    }

    public String list() {
        if (getRequest().getRemoteUser() != null) {

            System.out.println("listing...");
            listCatalog();
            carts = cartManager.getAll();
            return SUCCESS;
        } else {
            errorMessage(getText("login.error"));
            return ERROR;
        }
    }

    public String helpList() {
        return SUCCESS;
    }

    public String help() {
        return SUCCESS;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public String saveCartDescription() {
        System.out.println("NAME: " + name);
        System.out.println("id: " + getRequest().getAttribute("id"));
        System.out.println("d: " + getRequest().getAttribute("cart"));

        return SUCCESS;
    }
    private String cartName;
    private String cartDescription;

    /**
     * @return the cartName
     */
    public String getCartName() {
        return cartName;
    }

    /**
     * @param cartName the cartName to set
     */
    public void setCartName(String cartName) {
        this.cartName = cartName;
    }

    /**
     * @return the cartDescription
     */
    public String getCartDescription() {
        return cartDescription;
    }

    /**
     * @param cartDescription the cartDescription to set
     */
    public void setCartDescription(String cartDescription) {
        this.cartDescription = cartDescription;
    }

    /**
     * @return the requests
     */
    public List<RequestClient> getRequests() {
        return ((Cart) getSession().getAttribute("cart")).getRequests();
    }

    public List<RequestClient> getRequestsSaved() {
        List<RequestClient> rs = new ArrayList<RequestClient>();
        for (RequestClient c : requestClientManager.getAll()) {
            if (c.getCart().getUser().equals(userManager.getUserByUsername(getRequest().getRemoteUser()))) {
                rs.add(c);
            }
        }

        return rs;
    }

    /**
     * @return the listCategories
     */
    public List<Category> getListCategories() {
        return listCategories;
    }

    /**
     * @param listCategories the listCategories to set
     */
    public void setListCategories(List<Category> listCategories) {
        this.listCategories = listCategories;
    }
}